package com.ltba.rf.control.html;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Node;
import org.xml.sax.SAXException;

import com.ltba.common.html.connection.ConnectionUtil;
import com.ltba.rf.control.thread.RealTimeData;
import com.ltba.rf.view.BrowserPanel;

public class EarthquakeSenser {

	private static final String UPD_TIME = "情報発表時刻";
	private static final String ORIGIN = "震源地";

	@SuppressWarnings("unchecked")
	public static RealTimeData getData() throws IOException, SAXException {

		String upd = null;
		String origin = null;
		String max = null;

		HttpURLConnection conn = ConnectionUtil.getConnection(
				BrowserPanel.DEFAULT_URL, null);
		Document doc = ConnectionUtil.parse(conn);

		List<Node> nodes = (List<Node>) doc
				.selectNodes("//*[@class='yjw_table']/*");

		if (null == nodes || nodes.size() < 2)
			return null;

		Iterator<Node> drs = (Iterator<Node>) nodes.get(0).selectNodes("./*")
				.iterator();
		while (drs.hasNext()) {
			Node node = drs.next();
			if (null == upd)
				upd = getTrData(UPD_TIME, node);
			if (null == origin)
				origin = getTrData(ORIGIN, node);

			if (null != upd && null != origin) {
				break;
			}
		}

		Node degNode = nodes.get(1).selectSingleNode("./*/*");
		max = degNode.getStringValue();

		if (null != upd && null != max && null != origin) {
			return new RealTimeData(upd, origin, max);
		}

		return null;
	}

	private static String getTrData(String name, Node tr) {
		if (null != tr && tr.getStringValue().contains(name)) {
			return tr.getStringValue().replace(name, "").trim();
		}
		return null;
	}

}
